<?php
N::loadClass('N_Dispatcher_Interface');
class N_Dispatcher_Standard implements N_Dispatcher_Interface 
{
	/**
	 * 请求的URL
	 *
	 * @var string
	 */
	protected $_requestUrl;
	
	/**
	 * 额外的信息,目前只对PATH_INFO模式有效
	 *
	 * @var string
	 */
	protected $_extraInfo;
	
	/**
	 * 请求的控制器名
	 *
	 * @var string
	 */
	protected $_controllerName;
	
	/**
	 * 请求的动作名
	 *
	 * @var string
	 */
	protected $_actionName;
	
	/**
	 * 路由URL请求到指定控制器
	 *
	 */
	public function dispatching()
	{
		$this->_parseRequest();
		N::loadClass($this->_controllerName);
		$conObject = new $this->_controllerName;
		$action = $this->_actionName;
		$conObject->$action();
		//call_user_func(array($conObject, $action));
	}
	
	/**
	 * 解析URL请求
	 *
	 */
	protected function _parseRequest()
	{
		//对于转发的请求,至少要设置控制器名
		if (!empty($this->_controllerName))
		{
			return;
		}
		$urlMode = N::getIni('URL_MODE');
		switch ($urlMode)
		{
			case URL_STANDARD:
				{
					$this->_requestInfo = $_GET;
					$controllerTrigger = N::getIni('CONTROLLER_TRIGGER');
					$actionTrigger = N::getIni('ACTION_TRIGGER');
					$this->_controllerName = isset($this->_requestInfo[$controllerTrigger]) ? $this->_requestInfo[$controllerTrigger]
					: N::getIni('DEFAULT_CONTROLLER');
					$this->_actionName = isset($this->_requestInfo[$actionTrigger]) ? $this->_requestInfo[$actionTrigger]
					: N::getIni('DEFAULT_ACTION');
				}
				break;
			case URL_PATHINFO:
				$this->_parsePathInfoUrl();
				break;
			case URL_REWRITE:
				$this->_parseRewreiteUrl();
				break;
			default:
				break;
		}
		$this->_controllerName = N::getIni('APP_ROOT').CS.N::getIni('CONTROLLER_PREFIX').CS.$this->_controllerName;
		$this->_actionName = N::getIni('ACTION_PREFIX').ucfirst($this->_actionName);
	}
	
	/**
	 * 解析PATH_INFO模式下的URL,子类可重载该方法,以实现自己的URL规则
	 *
	 */
	protected function _parsePathInfoUrl()
	{
		$this->_requestInfo = $_SERVER['PATH_INFO'];
		if (empty($this->_requestInfo))
		{
			$this->_controllerName = N::getIni('DEFAULT_CONTROLLER');
			$this->_actionName = N::getIni('DEFAULT_ACTION');
		}
		else
		{
			//默认以/分割额外信息
			$info = explode('/', $this->_requestInfo);
			$size = count($info);
			if ($size == 1)
			{
				$this->_controllerName = $info[0];
				$this->_actionName = N::getIni('DEFAULT_ACTION');
			}
			else if ($size >= 2)
			{
				$this->_controllerName = $info[0];
				$this->_actionName = $info[1];
			}
		}
	}
	
	/**
	 * 解析Rewrite模式下的URL,子类可重载该方法,以实现自己的URL规则
	 *
	 */
	protected function _parseRewreiteUrl()
	{
		//Todo
	}
	
	/**
	 * 设置控制器名
	 *
	 * @param string $controller
	 */
	protected function setController(string $controller)
	{
		$this->_controllerName = $controller;
	}
	
	/**
	 * 设置动作名
	 *
	 * @param string $action
	 */
	protected function setAction(string $action)
	{
		$this->_actionName = $action;
	}
}